"""
@Time ： 2021/11/24 17:36
@Auth ： ChenZhangKun
"""
from socket import *


def send_file_to_client(new_client_socket, client_addr):
    # f发过来的文件名
    file_name = new_client_socket.recv(1024).decode("utf-8")
    print("需要下载的文件名是 %s =" % file_name)
    content = None
    # 打开文件读取数据
    try:
        f = open(file_name, "rb")
        # 读数据
        content = f.read()
    except Exception as ret:
        print("没有要下载的文件")
        print(ret)
    if content:
        new_client_socket.send(content)


def main():
    port = 8080
    # 创建套接字
    tcp_server = socket(AF_INET, SOCK_STREAM)
    tcp_server.bind(("", port))
    # 监听
    tcp_server.listen(128)
    while True:
        # 接收消息
        new_client_socket, client_addr = tcp_server.accept()
        # 发送数据
        send_file_to_client(new_client_socket, client_addr)
        # 关闭套接字
        new_client_socket.close()
    tcp_server.close()

if __name__ == '__main__':
    main()